package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eic.framework.core.service.ServiceCacheImpl;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.dao.SysDept;
import com.ruoyi.system.domain.dao.SysUser;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysSeqService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 部门管理 服务实现
 * 
 * @author ruoyi
 */
@Service
public class SysDeptServiceImpl extends ServiceCacheImpl<SysDeptMapper,SysDept> implements ISysDeptService
{
    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private ISysSeqService sysSeqService;

    @Override
    public boolean insert(SysDept entity) {
        SysDept parent = getById(entity.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(parent.getStatus())){
            throw new ServiceException("部门停用，不允许新增");
        }
        if(StringUtils.isBlank(parent.getAncestors())){
            entity.setAncestors(entity.getParentId());
        }else{
            entity.setAncestors(parent.getAncestors() + "," + entity.getParentId());
        }
        entity.setDeptId(sysSeqService.nextDeptId());
        return super.insert(entity);
    }
    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts)
    {
        return TreeSelect.buildTree(depts,SysDept::getDeptId,SysDept::getParentId,SysDept::getDeptName);
    }
    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(String deptId)
    {

        long result =deptMapper.selectCount(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getParentId,deptId));
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(String deptId)
    {
        long result = userMapper.selectCount(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getDeptId,deptId));
        return result > 0;
    }

}
